package org.springblade.tms.global.utils;


import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;

/**
 * @author gw_chenlp2
 * @Description
 * @Version 1.0
 * @date 2021-12-17 17:44
 */
@Slf4j
public class Obj2UrlParamUtils {
	public static String objToString(Object obj) {
		StringBuffer buffer = new StringBuffer();
		// 获取f对象对应类中的所有属性域
		int count = 0;
		Field[] fields = obj.getClass().getDeclaredFields();
		for (int i = 0, len = fields.length; i < len; i++) {
			String varName = fields[i].getName();
			//类生成的uuid不需要

			//仅需要第一次时拼接：?
			if (count == 0) {
				buffer.append("?");
				count = count + 1;
			}
			try {
				//获取原来的访问控制权限
				boolean accessFlag = fields[i].isAccessible();
				//修改访问控制权限
				fields[i].setAccessible(Boolean.TRUE);
				//获取在对象f中属性fields[i]对应的对象中的变量
				Object o = fields[i].get(obj);
				if (o != null && i == len - 1) {
					buffer.append(varName).append("=").append(o);
				} else if (o != null) {
					buffer.append(varName).append("=").append(o).append("&");
				}
				// 恢复访问控制权限
				fields[i].setAccessible(accessFlag);
			} catch (IllegalArgumentException | IllegalAccessException ex) {
				log.error("access log error", ex);
			}
		}
		return buffer.toString();
	}
}
